window.onpageshow = function (e) {
  if (e.persisted) {
    window.location.reload()
  }
};

import 'vux/src/styles/reset.less';
import './member.scss'
import 'vux/src/styles/close.less';


import {
  XDialog,
  Badge,
  Group,
  Cell,
  Confirm,
  ToastPlugin,
  ConfirmPlugin,
  Qrcode,
  XInput,
  XButton,
  Swiper,
  Scroller,
  Tab,
  TabItem,
  Sticky,
  Flexbox,
  FlexboxItem,
  CheckIcon,
  PopupPicker,
  XAddress,
  Datetime,
  TransferDomDirective as TransferDom
} from 'vux'
Vue.use(ToastPlugin)
Vue.use(ConfirmPlugin)



import bus from 'js/bus.js'
import axios from 'axios'

import utils from 'js/utils.js'

import {
  cookie
} from 'vux'

import {
  fetch,
  rap
} from 'js/fetch.js'

let url = {
  getSites: 'api/provinces',
  postLogout: 'api/logout',
  getUserInfo: 'api/user/info',
  avatar: 'api/user/avatar',
  refund: 'api/return/deposit',
  postPassword: 'api/user/update/password',
  postCode: 'api/sms/code',
  postCash: 'api/cash',
  getAreas: 'api/areas',
  edit: 'api/user'
}

const countTime = 60 //倒数计时60秒

url = rap(url)
import Myhead from 'components/head/head.vue'
// import Slide from 'components/slide/slide.vue'
import Top from 'components/top/top.vue'
// import Search from 'components/search/search.vue'
import Foot from 'components/foot/foot.vue'

import mixin from 'js/mixin.js'

new Vue({
  el: '#body',
  data: {
    wechatNumber: '',
    show3: false,
    IDCard: '',
    money: '',
    img: require('./imgs/head.png'),
    demo2: true,
    isLogin: false,
    token: '',
    userInfo: '',
    deposit: 0,
    expired: '',
    isExpired: 1,
    showQrcode: false,
    qrcodeValue: 'http://www.baidu.com',
    isshow: false,
    isshow1: false,
    code: '',
    codeMessage: '发送验证码',
    clock: false,
    phone: '',
    newPassword: '',
    cash: '',
    isShowInfo: false,
    name: '',
    birthDay: '',
    genderList: [{
      name: '男',
      value: '1'
    }, {
      name: '女',
      value: '2'
    }],
    childGender: [], //孩子性别
    addressData: [],
    address: [], //省市区
    detailAddress: '', //详细地址
    sites: [], //站点
    siteslist: [], //站点数据
    isEdit: false,
    title: '用户',
    isShowMoney: false,
    lerrerNumber: '',
    IDCardCheck: function (value) {
      return {
        valid: utils.isIDCard(value),
        msg: '请输入正确的证件号'
      }
    }
  },
  created() {
    // if(!!window.localStorage.getItem('lerrerNumber',this.lerrerNumber)){
    //   this.
    // }
    window.localStorage.removeItem('siteName')
    window.localStorage.removeItem('siteID')

    this.isLogin = utils.isLogin()
    //没有登录去登录
    //if (!this.isLogin) {
    // window.location.href = './login.html'
    //} else {
    //this.token = cookie.get('token').replace("bearer","")

    this.token = cookie.get('token')
    this.getUserInfo()
    this.getAreas()

    bus.$on('lerrerNumber', (e) => {
      //console.warn('----')
      //console.warn(e)
      this.lerrerNumber = e
    })




  },
  methods: {

    showMoney() {

      this.isShowMoney = !this.isShowMoney
    },
    getName(ids, names) {
      this.addressName = `${names[0]} ${names[1]} ${names[2]}`
      let address = `${names[0]} ${names[1]} ${names[2]}`
      let addressId = `${ids[0]},${ids[1]},${ids[2]}`

      this.addressName = address
      this.address_ids = addressId
    },
    getSites(boolean) {
      if (boolean) {
        //console.log(this.address)
        //获取站点
        fetch('get', url.getSites + '/' + this.address[2] + '/sites').then(res => {
          if (res.status >= 200 && res.status <= 300) {
            let array = []
            res.data.forEach(element => {
              array.push({
                name: element.name,
                value: element.id + ''
              })
              if (this.sites[0] == element.id) {
                window.localStorage.setItem('siteName', element.name)
                window.localStorage.setItem('siteID', element.id)
              }
            });



            this.$set(this, 'siteslist', array);

            // this.$vux.toast.show({
            //   text: '登录成功',
            //   type: 'success',
            //   onShow() {
            //     //console.log('Plugin: I\'m showing')
            //   },
            //   onHide() {
            //     window.location.href='./member.html'
            //     //console.log('Plugin: I\'m hiding')
            //   }
            // })
          } else {
            this.$vux.toast.show({
              text: res.data.message,
              type: 'warn'
            })
          }
        })
      }
    },
    getAreas() {
      //获取有站点的省市区
      fetch('get', url.getAreas).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          res.data.forEach((item, index) => {
            let obj = {}
            obj.value = item.id + ''
            obj.name = item.name
            if (!!item.parent_id) {
              obj.parent = item.parent_id + ''
            }
            //补全台湾省
            if (item.id == '710000') {
              this.addressData.push({
                name: '--',
                value: '710001',
                parent: '710000',
              })
              this.addressData.push({
                name: '--',
                value: '710002',
                parent: '710001',
              })
            }
            //补全香港
            if (item.id == '810000') {
              this.addressData.push({
                name: '--',
                value: '810001',
                parent: '810000',
              })
              this.addressData.push({
                name: '--',
                value: '810002',
                parent: '810001',
              })
            }
            //补全澳门
            if (item.id == '820000') {
              this.addressData.push({
                name: '--',
                value: '820001',
                parent: '820000',
              })
              this.addressData.push({
                name: '--',
                value: '820002',
                parent: '820001',
              })
            }
            //console.log(obj)

            if (item.name == '市辖区' && (item.parent_id != '110000' && item.parent_id != '310000' && item.parent_id != '120000' && item.parent_id != '500000')) {

            } else {
              this.addressData.push(obj)
            }
          })
          //console.log(this.addressData)
        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn'
          })
        }
      })
    },
    checkTel(value) {
      this.isCheckTel = checkphone(value)
      return {
        valid: this.isCheckTel,
        msg: '请输入合格的手机号'
      }
    },
    sendCode() {
      //发送验证码      
      fetch('post', url.postCode, {
        phone: this.phone,
        type: 'pass'
      }).then(res => {

        if (res.status >= 200 && res.status <= 300) {

          //cookie.set('token', res.data.token)
          this.$vux.toast.show({
            text: '验证码发送成功',
            onHide() {}
          })
        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })
    },
    countDown() {
      //倒计时
      //console.log(1)
      if (this.clock) {
        return
      }
      if (this.phone == '') {
        return
      }
      this.sendCode()
      this.clock = true
      let _this = this;
      this.codeMessage = countTime
      let countDown = setInterval(function () {
        //console.log(_this.codeMessage)
        if (_this.codeMessage <= 1) {
          _this.codeMessage = '发送验证码'
          _this.clock = false
          clearInterval(countDown)
          return
        }
        _this.codeMessage--
      }, 1000)
    },
    changeShow() {
      //修改密码
      let _this = this // 需要注意 onCancel 和 onConfirm 的 this 指向
      this.isshow = true
    },
    changePassword() {
      //修改密码
      let _this = this // 需要注意 onCancel 和 onConfirm 的 this 指向
      this.isshow = true
      if (this.phone == '' || this.code == '') {
        return
      } else {

        fetch('post', `${url.postPassword}`, {
          code: this.code,
          password: this.newPassword
        }, {
          'headers': _this.token
        }).then(res => {
          if (res.status >= 200 && res.status <= 300) {
            _this.$vux.toast.show({
              text: '密码修改成功',
              onShow() {
                //console.log('Plugin: I\'m showing')
              },
              onHide() {
                window.location.href = window.location.href
              }
            })

          } else {
            _this.$vux.toast.show({
              text: res.data.message,
              type: 'warn',
              onShow() {
                //console.log('Plugin: I\'m showing')
              },
              onHide() {
                //console.log('Plugin: I\'m hiding')
              }
            })
          }
        })

      }





    },
    refund() {
      //退押金
      let _this = this // 需要注意 onCancel 和 onConfirm 的 this 指向


      fetch('post', `${url.refund}`, {
        wx_id: this.wechatNumber
      }, {
        'headers': _this.token
      }).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          _this.$vux.toast.show({
            text: '申请退押金成功，工作人员会在3个工作日内审核处理',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              window.location.href = window.location.href
            }
          })

        } else {
          _this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })

      // _this.$vux.confirm.show({
      //   title: '退押金',
      //   content: '您确定要退押金吗？',
      //   onConfirm() {

      //   }
      // })
    },
    changeshow1() {
      this.isshow1 = true
    },
    withdraw() {
      //退提现
      //this.
      let _this = this
      var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      if (reg.test(this.money)) {
        //
        fetch('post', `${url.postCash}`, {
          amount: this.money
        }, {
          'headers': _this.token
        }).then(res => {
          if (res.status >= 200 && res.status <= 300) {
            _this.$vux.toast.show({
              text: '申请退押金成功，工作人员会在3个工作日内审核处理',
              onShow() {
                //console.log('Plugin: I\'m showing')
              },
              onHide() {
                //console.log('Plugin: I\'m hiding')
              }
            })

          } else {
            _this.$vux.toast.show({
              text: res.data.message,
              type: 'warn',
              onShow() {
                //console.log('Plugin: I\'m showing')
              },
              onHide() {
                //console.log('Plugin: I\'m hiding')
              }
            })
          }
        })
        //
      } else {
        _this.$vux.toast.show({
          text: '请输入正确的金额',
          type: 'warn',
          onShow() {
            //console.log('Plugin: I\'m showing')
          },
          onHide() {
            //console.log('Plugin: I\'m hiding')
          }
        })
      }
    },
    cashcheck(v) {
      var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      // if(reg.test(cash)){

      // }else{

      // }

      //console.log(v)
    },
    editHeader(e) {
      this.$refs.myinput.click()
    },
    upimage(e) {
      let _this = this
      var file = e.target.files[0];
      let param = new FormData()
      if (file.size > 1024 * 1024 * 2) {
        _this.$vux.toast.show({
          text: '大小不能超过2M',
          type: 'warn',
          onShow() {
            //console.log('Plugin: I\'m showing')
          },
          onHide() {
            //console.log('Plugin: I\'m hiding')
          }
        })
        return
      }
      param.append('avatar', file, file.name)
      //console.log(param.get('file'))
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      axios.post(`${url.avatar}`, param, config)
        .then(res => {
          if (res.status >= 200 && res.status <= 300) {
            // /console.log(this.$refs.avatar.src)
            //console.log(res.data.avatar)
            this.$refs.avatar.src = res.data.avatar
            //this.img=res.data
            //console.log(res.data)
          } else {
            _this.$vux.toast.show({
              text: res.data.message,
              type: 'warn',
              onShow() {
                //console.log('Plugin: I\'m showing')
              },
              onHide() {
                //console.log('Plugin: I\'m hiding')
              }
            })
          }
        })
    },
    shareQrcode() {
      //分享二维码
      //alert(this.userInfo.id) this.userInfo

      this.showQrcode = true
      //window.location.href = `./spread.html?user_id=${this.userInfo.id}`
    },
    nofind(e) {
      e.target.src = this.img
    },
    logout() {
      let _this = this // 需要注意 onCancel 和 onConfirm 的 this 指向
      this.$vux.confirm.show({
        title: '退出',
        content: '您确定要执行退出操作吗？',
        onConfirm() {
          fetch('post', `${url.postLogout}`, {}, {
            'headers': _this.token
          }).then(res => {
            if (res.status >= 200 && res.status <= 300) {
              cookie.remove('token')
              window.localStorage.removeItem('siteName')
              window.localStorage.removeItem('siteID')
              window.localStorage.removeItem('deposit')
              window.localStorage.removeItem('isExpired')
              window.location.href = './index.html'
            } else {
              _this.$vux.toast.show({
                text: res.data.message,
                type: 'warn',
                onShow() {
                  //console.log('Plugin: I\'m showing')
                },
                onHide() {
                  //console.log('Plugin: I\'m hiding')
                }
              })
            }
          })
        }
      })
    },
    pay() {
      //支付押金
      fetch('post', `${url.postDeposit}`, {}, {
        'headers': this.token
      }).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          //console.log(res.data)
          let json = JSON.parse(res.data.config)
          console.log(json)
          WeixinJSBridge.invoke(
            'getBrandWCPayRequest', json,
            function (res) {
              if (res.err_msg == "get_brand_wcpay_request:ok") {
                // 使用以上方式判断前端返回,微信团队郑重提示：
                // res.err_msg将在用户支付成功后返回
                // ok，但并不保证它绝对可靠。
                alert('支付成功')
                window.location.href = './member.html'
              }
            }
          );


        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })
    },
    save() {
      let _this = this;
      //alert(1)
      //this.isEdit=false;
      //修改
      if (!!_this.IDCard) {
        if (!(utils.isIDCard(_this.IDCard))) {
          _this.$vux.toast.show({
            type: 'warn',
            text: '请输入正确的身份证号',
            onHide() {
              //window.location.href = "./buy_member.html"
            }
          })
          return
        }

      }


      fetch('post', url.edit, {
        id_card: this.IDCard,
        name: this.name,
        address: this.addressName,
        address_ids: this.address_ids,
        detail_address: this.detailAddress,
        site_id: this.sites[0],
        child_gender: this.childGender[0],
        child_birthday: this.birthDay
      }, {
        'headers': _this.token
      }).then(res => {

        if (res.status >= 200 && res.status <= 300) {
          _this.$vux.toast.show({
            text: '保存成功',
            onHide() {
              _this.isEdit = false;

              window.location.href = window.location.href
            }
          })
        } else {
          _this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })
    },
    getUserInfo() {
      //获取用户信息
      fetch('get', `${url.getUserInfo}`, {}, {
        'headers': this.token
      }).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          //res.data.address='江苏 无锡 南长'
          //res.data.address_ids='320000,320200,320213'
          this.userInfo = res.data
          this.IDCard = this.userInfo.id_card
          this.address = this.userInfo.address_ids.split(',')

          this.detailAddress = this.userInfo.detail_address

          if (this.sites[0] != '') {
            this.sites[0] = this.userInfo.site_id
            //console.log('---')
            //console.log(this.sites[0])
            this.getSites(true)
          }

          this.money = this.userInfo.balance
          //this.qrcodeValue = `http://www.5chelib.com?callback=http://www.5chelib.com/mobile/dist/index.html&user_id=${this.userInfo.id}`
          this.qrcodeValue = `https://www.5chelib.com/mobile/dist/spread.html?user_id=${this.userInfo.id}`
          //window.location.href = `./spread.html?user_id=${this.userInfo.id}`

          setTimeout(() => {
            var shareContent = document.querySelector("#canvas");
            var width = shareContent.clientWidth;
            var height = shareContent.clientHeight;
            //console.log(width)
            //console.log(height)
            var canvas = document.createElement("canvas");
            var scale = 2;
            var content2 = $(shareContent).clone(true);

            canvas.width = width * scale;
            canvas.height = height * scale;
            canvas.getContext("2d").scale(scale, scale);
   

            var opts = {
              scale: scale,
              canvas: canvas,
              //logging: true,
              width: width,
              height: height,
              useCORS: true
            };
            html2canvas(shareContent, opts).then(function (canvas) {

              //var context = canvas.getContext("2d");

              var img = Canvas2Image.convertToImage(
                canvas,
                canvas.width,
                canvas.height
              );
              console.log(img)

              //document.querySelector("#share .warpper").style.border = "0";
              //document.querySelector("#share .warpper").style.padding = "0";
              document.querySelector(".img-box").innerHTML = "";
              document.querySelector(".img-box").appendChild(img);
              //document.querySelector(".img-box").appendChild(canvas);
              $(img).css({
                width: "100%"
                //height: canvas.height  + "px"
              });
            });
          }, 2000);

          //console.log(this.userInfo)
          //
          this.phone = this.userInfo.phone
          //this.lerrerNumber = window.localStorage.getItem('lerrerNumber')

          this.deposit = Number(this.userInfo.deposit)

          if (res.data.user_vip == null) {
            this.expired = '亲,您当前还不是会员'
            window.localStorage.setItem('isExpired', 1)
            this.isExpired = 1
          } else if (res.data.user_vip.expired == null) {
            this.expired = '超级会员'
            window.localStorage.setItem('isExpired', 0)
            this.isExpired = 0
          } else if (new Date().valueOf() > new Date(res.data.user_vip.expired).valueOf()) {
            this.expired = this.userInfo.user_vip.expired + '(过期)'
            window.localStorage.setItem('isExpired', 1)
            this.isExpired = 1
          } else {
            this.expired = this.userInfo.user_vip.expired
            window.localStorage.setItem('isExpired', 0)
            this.isExpired = 0
          }
          window.localStorage.setItem('deposit', res.data.deposit)
          //获取用户修改表信息
          this.name = this.userInfo.name
          this.birthDay = this.userInfo.child.birthday
          this.childGender.push(this.userInfo.child.gender + '')



          //.deposit=res.data.deposit
        } else if (res.status == 401) {
          //cookie.remove('token')
          //window.location.href='./login.html'
        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })
    },
    show(index) {
      if (this.listIndex > index) {
        this.transitionName = 'slide-right'
      } else {
        this.transitionName = 'slide-left'
      }
      this.listIndex = index
    }
  },
  directives: {
    TransferDom
  },
  components: {
    Badge,
    Group,
    Cell,
    XDialog,
    Qrcode,
    Confirm,
    XInput,
    XButton,
    Swiper,
    Scroller,
    Tab,
    TabItem,
    Sticky,
    Flexbox,
    FlexboxItem,
    CheckIcon,
    PopupPicker,
    XAddress,
    Datetime
  },
  mixins: [mixin]
})
